<template>
  <div class="content_box">
    <!-- 已选择房间 -->
    <div class="change_room">
      <div class="box">
        <p><img src="/static/images/time_slot_icon1.png" alt="">所属店铺</p>
        <p>{{msg.storeName}}</p>
      </div>
      <!-- <div class="box">
        <p><img src="/static/images/dianpuguanli.png" alt="">已选房间</p>
        <p>{{msg.name}}</p>
      </div> -->
    </div>
    <!-- 通知 -->
    <van-notice-bar
      color="#FE6E34"
      background="#FFE8E3"
      left-icon="volume-o"
      :text="msg.lowConsumeTime/60+'小时起订，灰色为已被预定，可提前7天预定'"
    />
    <!-- 时间日期 -->
    <div class="tab_time_box">
      <div @click="dateClick(index)" :class="dateListIndex == index?'on box':'box'" v-for="(item,index) in dateList" :key="index">
        <p class="text">{{item.week}}</p>
        <p class="day">{{item.day}}</p>
      </div>
    </div>
    <p class="line"></p>
    <!-- 时间表列表 -->
    <div class="timetable_box">
      <div class="time_slot">
        <div class="time_duan">
          <block v-for="(item, index) in timeSlotList" :key="item.id">
            <div
              :class="item.state && item.isSelect ? 'on' : !item.isSelect ? 'on_on' : ''"
              @click="timeClick(index,item)"
              v-if="item.i_index == dateListIndex"
            >
              <p class="text"><span>￥</span>{{msg.price/2}}</p>
              <p class="time">{{ item.time.shiftTime }}</p>
              <!-- <p class="text_qk" v-else-if="item.isClean">清洁时间</p>
              <p class="text" v-else>已预约</p> -->
              <p class="man" v-if="!item.isSelect">满</p>
              <!-- <p class="man" v-if="item.isClean">
                <img src="/static/images/ds.png" alt="" />
              </p> -->
              <p class="qi" v-if="item.start">起</p>
              <p class="qi" v-if="item.end">止</p>
            </div>
          </block>
        </div>
        <div
          class="button_box1"
          :style="{ paddingBottom: isIphoneXnum + 'px' }"
        >
          <div class="left">
            <p class="time">共{{timeLength}}小时</p>
            <p class="price">￥<span>{{totlePrice}}</span></p>
          </div>
          <p class="button on" @click="submit" v-if="timeLength">立即预定</p>
          <p class="button" v-else>立即预定</p>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import {
  dayTime,
  dayMinutes,
  lineTime,
  toYuyueTime,
  dateFormat,
  Debounce
} from "@/utils";
import { getRoomWeekTime,saveOrder} from "@/api/index";
export default {
  data(){
    return{
      dateListIndex:0,
      dateList:[],
      indexArr:[],
      timeLength:0,
      isIphoneXnum:0,
      msg:{},
      timeSlotList:[],
      day:'',
      totlePrice:0,
      lastIndex:0,
      targetOrderId:''
    }
  },
  
  methods: {
    // 立即预定
    submit(){
      if(!this.timeLength){
        this.$toast('请选择时间区域~')
        return
      }
      // if(this.timeLength < this.msg.lowConsumeTime/60){
      //     this.$toast(`亲，最低${this.msg.lowConsumeTime/60}小时起约`)
      //   return
      // }
      let data = {
        endTime: this.msg.apiEndTime,
        startTime: this.msg.apiStartTime,
        roomId: this.msg.roomId,
        targetOrderId:this.targetOrderId
      }

      console.log(data)
      // return
      this.$showLoading('加载中...')
      saveOrder(data).then(res=>{
        if(res.statusCode == '00000'){
          wx.navigateTo({
            url: `/pages/confirm_order/main?id=${res.data}`,
          });
          wx.hideLoading()
        }else{
          wx.hideLoading()
          this.$toast(res.message)
        }
      })
    },

    // 日期点击切换
    dateClick(index){
      this.dateListIndex = index
    },

    // 截取当前点击时间
    getInterceptTime(index){
      let oneDay = this.dateList[index]
      let arr = oneDay.month.split(".");
      return `${oneDay.year}-${arr[0]}-${arr[1]} 00:00:00`
    },


    // 获取一周的时间
    getWeeksDate(){
      getRoomWeekTime({roomId:this.msg.roomId}).then(res=>{
        if(res.statusCode == '00000'){
          this.dateList = []
          this.timeSlotList = []

          let weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
          res.data.map((item,index)=>{
            let riqi = new Date(item.day)
            this.dateList.push({
              year:item.day,
              day:item.day.split('-')[1]+'.'+item.day.split('-')[2],
              week:weeks[riqi.getDay()]
            })
            this.dateList[0].week = '今天'
            item.times.map((child,i)=>{
              child.i_index = index
              child.id = i
              child.day = item.day
              this.timeSlotList.push(child)
            })
          })
          console.log(this.dateList)
        }
      })
    },

    // 时间戳转换
    timestampToTime(timestamp) {
      var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1) + '-';
      var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate())+ ' ';
      var h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours())+ ':';
      var m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes());
      var s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
      return Y+M+D+h+m;
    },

    /*时间表-时间段选择*/
    timeClick(index, item) {
      console.log(item)
      // 预约状态
      if (!item.isSelect) {
        return;
      }
      // 时间长度
      this.timeLength = 0
      // 如果有选着的默认先把值清空
      console.log(this.lastIndex)
      if(this.lastIndex){
        for(let i = 0 ; i < this.lastIndex+1 ; i++){
          this.timeSlotList[i].state = false;
          this.timeSlotList[i].start = false;
          this.timeSlotList[i].end = false;
          this.timeSlotList[i].title = '空闲';
        }
      }
      // this.timeSlotList.map((res) => {
      //   res.state = false;
      //   res.start = false
      //   res.end = false
      //   res.title = "空闲";
      // });
      // 添加选中的下标
      this.indexArr.unshift(index);
      // 选中的第一个
      var firstIndex = this.indexArr[this.indexArr.length - 1];
      // 选中的最后一个
      this.lastIndex = this.indexArr[0];
      console.log(this.indexArr[0])
      // 取选中个数:如果大于证明是点击前面的时间,然后把值清空
      let len = 0;
      if (firstIndex <= this.lastIndex) {
        len = this.lastIndex - firstIndex;
      } else {
        item.state = true;
        item.start = true;
        item.title = "已选";
        this.$set(this.timeSlotList, index, item);
        // 删除第一个下标,保证可以继续联动选择
        if (this.indexArr.length >= 2) {
          this.indexArr = this.indexArr.slice(0, 1);
        }
        return;
      }

      

      // 第一次选择或者重新选择
      if (!len) {
        // 先清空时间表
        for(let i = 0 ; i < this.lastIndex+1 ; i++){
          this.timeSlotList[i].state = false;
          this.timeSlotList[i].start = false;
          this.timeSlotList[i].end = false;
          this.timeSlotList[i].title = '空闲';
        }
        if (this.indexArr.length > 1) {
          this.indexArr = [];
        } else {
          // 当前点击的时间表赋值
          item.state = true;
          item.start = true;
          item.title = "已选";
          this.$set(this.timeSlotList, index, item);
        }
      } else {
        // 判断选择中包含有别人预约的时间段
        let changeArr = []
        for(let i = firstIndex ; i < this.lastIndex ; i++){
          changeArr.push(this.timeSlotList[i])
        }
        let c_index = changeArr.findIndex(cItem => cItem.status == true)
        if(c_index != -1){
          this.$toast('包含别人预约时间段~')
          this.indexArr = [];
         return
        }
   
        // 第一个到最后一个为选中状态
        for (let i = 0; i < len + 1; i++) {
          this.timeSlotList[firstIndex + i].state = true;
          this.timeSlotList[firstIndex + i].title = "已选";
        }

        // 添加"起","止"
        this.timeSlotList[firstIndex].start = true
        this.timeSlotList[firstIndex + len].end = true

        // 判断有没得orderId-时间交集
        if(this.timeSlotList[firstIndex].orderId){
          console.log("===targetOrderId===")
          console.log(this.timeSlotList[firstIndex].orderId)
          this.targetOrderId = this.timeSlotList[firstIndex].orderId
        }else{
          this.targetOrderId = ''
        }


        // 算选择好多小时
        let startTime = `${this.timeSlotList[firstIndex].day} ${this.timeSlotList[firstIndex].time.shiftTime}`
        // if(this.lastIndex){
        //   let newdate = new Date().getTime()
        //   console.log(newdate)
        //   let s_time = Date.parse(startTime);
        //   if(newdate>s_time){
        //     console.log("==大==")
        //     startTime = this.timestampToTime(newdate)
        //     console.log(startTime)
        //   }
        //   console.log(s_time)
        // }
        // ${this.timeSlotList[this.lastIndex].day}
        let endTime = `${this.timeSlotList[this.lastIndex].day} ${this.timeSlotList[this.lastIndex].time.shiftTime}`
        this.timeLength = this.getHour(`${startTime}:00`,`${endTime}:00`)

        this.totlePrice = (this.timeLength*this.msg.price).toFixed(2)
        // 传值到下个页面
        // let weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        // let riqi = new Date(this.timeSlotList[firstIndex].day)
        // let riqi1 = new Date(this.timeSlotList[this.lastIndex].day)
        console.log(startTime,endTime)
        let queryData = {
          // startTime:this.timeSlotList[firstIndex].day,
          // endTime:this.timeSlotList[this.lastIndex].day,
          // startTimeSlot:`${this.timeSlotList[firstIndex].time.shiftTime}`,
          // endTimeSlot:`${this.timeSlotList[this.lastIndex].time.shiftTime}`,
          // startWeek:weeks[riqi.getDay()],
          // endWeek:weeks[riqi1.getDay()],
          // timeLength:this.timeLength,
          // roomName:this.roomName,
          price:this.msg.price,
          roomId:this.msg.roomId,
          apiStartTime:`${startTime}:00`,
          apiEndTime:`${endTime}:00`,
          // storeName:this.msg.storeName,
          // roomName:this.msg.name,
          storeId: this.msg.storeId,
        }
        this.msg = Object.assign(this.msg,queryData)
        console.log(this.msg)
      }
    },

    // 算选择多少小时
    getHour(s1, s2) {
      var reDate = /\d{4}-\d{1,2}-\d{1,2} /;
      s1 = new Date((reDate.test(s1) ? s1 : '2018-1-1 ' + s1).replace(/-/g, '/'));
      s2 = new Date((reDate.test(s2) ? s2 : '2018-1-1 ' + s2).replace(/-/g, '/'));
      var ms = s2.getTime() - s1.getTime();
      if (ms < 0) return 0;
      return (ms / 1000 / 60 / 60).toFixed(1);  //小时
    },
  },
  onShow() {
  },
  onUnload() {
    console.log('退出')
    this.dateListIndex = 0
    this.timeSlotList = []
    this.indexArr = []
    this.totlePrice = 0
    this.timeLength = 0
    this.targetOrderId = ''
  },
  onLoad(options){
    console.log(options)
    this.targetOrderId = ''
    this.msg = JSON.parse(options.msg)
    this.getWeeksDate()

    //判断手机机型，动态给底部添加样式
    wx.getSystemInfo({
      success: (res) => {
        console.log("手机信息res" + res.model);
        let modelmes = res.model;
        if (
          modelmes.search("iPhone 14") != -1 ||
          modelmes.search("iPhone 13") != -1 ||
          modelmes.search("iPhone 12") != -1 ||
          modelmes.search("iPhone 11") != -1 ||
          modelmes.search("iPhone X") != -1 ||
          modelmes.search("iPhone XR") != -1 ||
          modelmes.search("iPhone XS") != -1
        ) {
          this.isIphoneXnum = 25;
        } else {
          this.isIphoneXnum = 0;
        }
      },
    });
  }
};
</script>

<style lang="scss" scoped>
.content_box {
  min-height: 100vh;
  padding-bottom: 100rpx;
  background: #fff;
  .change_room{
    .box{
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom:1px solid rgb(235, 235, 235);
      padding:0 30rpx;
      font-size:30rpx;
      color:#333;
      font-weight: bold;
      &:first-child{
        border-top:1px solid rgb(235, 235, 235);
      }
      p{
        display: flex;
        align-items: center;
      }
      img{
        width: 40rpx;
        height: 40rpx;
        margin-right:15rpx;
      }
    }
  }
  .tab_time_box{
    white-space: nowrap;
    overflow-x: auto;
    padding:20rpx 0;
    .box{
      display: inline-block;
      margin-right:30rpx;
      width: 110rpx;
      text-align: center;
      &:first-child{
        margin-left:20rpx;
      }
      .text{
        font-size:26rpx;
        color:#CACACA;
        margin-bottom:18rpx;
        font-weight: 500;
      }
      .day{
        color:#666666;
        font-size:30rpx;
        font-weight: 500;
      }
    }
    .on{
      background: #222222;
      color:#fff;
      padding:15rpx 0;
      border-radius: 10rpx;
      pointer-events:none;
      .text{
        color:#fff;
      }
      .day{
        color:#fff;
      }
    }
    &::-webkit-scrollbar {
      display: none;
    }
  }
  .line{
    width: 100%;
    height: 20rpx;
    background: #f8f8f8;
  }
  .timetable_box {
    .lanmu {
      margin: 0 30rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      margin-bottom: 30rpx;
      border-bottom: 2rpx solid #f4f4f4;
      .msg {
        font-size: 30rpx;
        color: #333;
        .title {
          font-weight: bold;
          display: flex;
          align-items: center;
          .line {
            display: inline-block;
            width: 6rpx;
            height: 30rpx;
            background: #02b4ae;
            margin-right: 10rpx;
          }
        }
        .text {
          margin-left: 30rpx;
          color: #999;
          font-size: 26rpx;
        }
      }
      .sjx {
        margin-right: 5px;
        display: flex;
        align-items: center;
        p {
          color: #999;
          font-size: 26rpx;
          margin-right: 5px;
        }
      }
    }
    .line_text {
      color: #999;
      font-size: 24rpx;
      padding: 0 30rpx;
      font-weight: 500;
    }
    .time_slot {
      .time_box {
        width: auto;
        overflow-x: auto;
        white-space: nowrap;
        background: #f5f5f5;
        box-shadow: 0px 2px 10px 2px rgba(40, 70, 91, 0.1);
        border-radius: 10rpx;
        margin: 20rpx 10rpx 20rpx 15rpx;
        padding: 20rpx 30rpx;
        &::-webkit-scrollbar {
          display: none;
        }
        div {
          display: inline-block;
          width: 140rpx;
          text-align: center;
          color: #333;
          font-size: 24rpx;
          padding: 10rpx 0;
          .time {
            font-size: 28rpx;
            margin-bottom: 5rpx;
          }
          &.on {
            background: #35c982;
            color: #fff;
            border-radius: 10rpx;
          }
        }
      }
      .time_duan {
        width: 92%;
        margin: 0 auto;
        padding: 30rpx 0;
        padding-bottom: 100rpx;
        // display: flex;
        // justify-content: space-between;
        // flex-wrap:wrap;
        // &:after{
        //   content: '';
        //   width: 330rpx;
        // }
        div {
          position: relative;
          color: #817e82;
          font-size: 24rpx;
          width: 158rpx;
          padding: 12rpx 0;
          display: inline-block;
          margin: 0rpx 18rpx 20rpx 0rpx;
          margin-bottom:20rpx;
          // border:1px solid #f5f5f5;
          text-align: center;
          border-radius: 20rpx;
          background: #F9F9FB;
          &:nth-child(4n){
            margin-right:0
          }
          .time{
            font-size:26rpx;
            margin-top:10rpx;
            color:#666666;
            font-weight: 500;
            font-family: 'FZSuXSLSJW';
          }
          .text{
            color:#3E3E3E;
            font-size:42rpx;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'FZSuXSLSJW';
            span{
              font-size:26rpx;
              font-weight: 500;
            }
          }
          .qi{
            position: absolute;
            bottom:0;
            right:0;
            width: 40rpx;
            height: 40rpx;
            line-height: 40rpx;
            background: #52732c;
            border-bottom-right-radius: 20rpx;
            border-top-left-radius: 20rpx;
            font-size:24rpx;
            color:#fff;
          }
          
          &:nth-child(4n){
            margin-right:0;
          }
          &.on {
            background: #92b46c;
            border-radius: 20rpx;
            .time{
              color:#fff;
            }
            .text{
              color:#fff;
            }
          }
          &.on_on {
            background: #f4f4f4;
            color: #959597;
            border-radius: 20rpx;
            border-color: #f4f4f4;
            .time{
              color:#959597;
            }
            .text{
              color:#959597;
            }
            .text_qk {
              display: flex;
              align-items: center;
              justify-content: center;
              img {
                width: 24rpx;
                height: 24rpx;
                margin-right: 10rpx;
              }
            }
          }
          .man{
            position: absolute;
            top:0;
            right:0;
            width: 42rpx;
            height: 36rpx;
            background: #969698;
            font-size:22rpx;
            color:#fff;
            text-align: center;
            border-top-right-radius: 20rpx;
            border-bottom-left-radius: 20rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            img{
              width: 26rpx;
              height: 26rpx;
            }
          }
        }
      }
      .button_box1 {
        padding:0 30rpx;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 92%;
        height: 146rpx;
        position: fixed;
        bottom: 0;
        border-top:1px solid #D9D9D9;
        .left {
          .time{
            color:#8FB162;
            font-size:26rpx;
          }
          .price{
            font-weight: 500;
            color:#333;
            font-size:32rpx;
            margin-top:10rpx;
            span{
              font-size:46rpx;
            }
          }
          div {
            display: flex;
            align-items: center;
            margin-right: 30rpx;
            font-size: 24rpx;
            color: #333;
            p {
              width: 22rpx;
              height: 22rpx;
              border-radius: 4rpx;
              border: 1px solid transparent;
              margin-right: 10rpx;
              &.blue {
                background: #02b4ae;
              }
              &.none {
                border-color: #f4f4f4;
              }
              &.disable {
                background: #f4f4f4;
              }
            }
          }
        }
        .button {
          width: 216rpx;
          height: 88rpx;
          line-height: 88rpx;
          background: #666666;
          text-align: center;
          border-radius: 4rpx;
          color: #fff;
          font-size: 30rpx;
          font-weight: 500;
          &.on{
            background: #222;
          }
        }
      }
    }
  }
}
</style>